import { mongo } from "../mogoConfig";



const run = async () => {
    const orderTB = mongo.db("my_test").collection("orders")

    const cursor1 = orderTB.aggregate([
        { $match: { size: "medium" } },
        { $group: { _id: "$name", totalQuantity: { $sum: "$quantity" } } }
    ])

    console.log("聚合结果1-----------------------")
    for await (const item of cursor1) {
        console.log(JSON.stringify(item))
    }


    const cursor2 = orderTB.aggregate([
        {
            $match: { date: { $gte: new Date(2020, 0, 30), $lt: new Date(2022, 0, 30) } }
        },
        {
            $group: {
                _id: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
                totalOrderValue: { $sum: { $multiply: ["$price", "$quantity"] } },
                averageOrderQuantity: { $avg: "$quantity" }
            }
        },
        {
            $sort: {
                totalOrderValue: -1
            }
        }
    ])

    console.log("聚合结果2-----------------------")
    for await (const item of cursor2) {
        console.log(JSON.stringify(item))
    }


}






run()
    .catch(error => {
        console.log(error)
    })
    .finally(() => {
        mongo.close()
        console.log("执行完成")
    })